using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.Query;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    public class SqlFunction : SqlEvaluatable, ISelectable
    {
        #region Member properties and fields
        private string _name;
        public string Name
        {
            get { return _name; }
        }

        private string _alias;
        public string Alias
        {
            get { return _alias; }
        }

        private List<IEvaluatable> _parameters = new List<IEvaluatable>();
        public List<IEvaluatable> Parameters
        {
            get { return _parameters; }
        }
        #endregion

        #region Constructors
        public SqlFunction(string name, string alias, params IEvaluatable[] parameters)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            _name = name;
            _alias = alias;
            _parameters.AddRange(parameters);
        }
        #endregion

        #region IRelationalElement Members

        public override string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }
        public override string ToSql(IQueryContext context)
        {
            StringBuilder sb = new StringBuilder(_name);
            sb.Append("(");
            for (int x = 0; x < _parameters.Count; x++)
            {
                if (x > 0) sb.Append(", ");
                sb.Append(Parameters[x].ToSql());
            }
            sb.Append(")");

            if (!string.IsNullOrEmpty(_alias))
            {
                sb.Append(" AS [");
                sb.Append(_alias);
                sb.Append("]");
            }

            return sb.ToString();
        }

        #endregion

        #region BNums
        public static SqlFunction Count(string alias)
        {
            return new SqlFunction("COUNT", alias, new SqlLiteral("*"));
        }
        public static SqlFunction Average(string alias, IColumn column)
        {
            return new SqlFunction("AVG", alias, column);
        }
        public static SqlFunction Sum(string alias, IColumn column)
        {
            return new SqlFunction("SUM", alias, column);
        }
        #endregion
    }
}
